//
//  RssController.m
//  XProgress
//
//  Created by Ondrej Rafaj on 20.8.09.
//  Copyright 2009 Home. All rights reserved.
//

#import "RssController.h"
#import "RssDetailController.h"
#import "ServerLocations.h"


@implementation RssController

@synthesize xmlPath;
@synthesize searchBar;
@synthesize searchString;
@synthesize startUrl;

@synthesize activityIndicator;





- (void) sendMessage:(NSString *) title aaaaa:(NSString *) message {
	UIAlertView * alertView = [[UIAlertView alloc] initWithTitle: title message: message delegate: nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
	[alertView show];
	[alertView release];	
}







- (void) parseXMLFileAtURL:(NSString *)URL {
	items = [[NSMutableArray alloc] init];
	
	//you must then convert the path to a proper NSURL or it won't work
	NSURL *xmlURL = [NSURL URLWithString:URL];
	
	// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
	// this may be necessary only for the toolchain
	xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
	
	// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
	[xmlParser setDelegate:self];
	
	// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
	[xmlParser setShouldProcessNamespaces:NO];
	[xmlParser setShouldReportNamespacePrefixes:NO];
	[xmlParser setShouldResolveExternalEntities:NO];
	
	[xmlParser parse];
}

- (void) doGetData {
	if ([items count] == 0) {
		[activityIndicator startAnimating];
		NSString * path = kXprogressArticles;
		unsigned int count = [startUrl length];
		if (count > 0) path = startUrl;
		unsigned int length = [searchString length];
		if (length > 0) {
			path = [path stringByAppendingString: @"?search="];
			path = [path stringByAppendingString: searchString];
		}
		[self parseXMLFileAtURL:path];
		[path release];
		[activityIndicator stopAnimating];
	}
}

- (void) searchBarSearchButtonClicked: (UISearchBar *) sb {
	[items removeAllObjects];
	searchString = [sb text];
	[NSThread detachNewThreadSelector:@selector(doGetData) toTarget:self withObject:nil];
	[searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)sb {
    [sb resignFirstResponder];
}



- (void)parserDidStartDocument:(NSXMLParser *)parser {
	NSLog(@"found file and started parsing");
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
	NSString * errorString = [NSString stringWithFormat:@"Unable to download dictionary database from web site (Error code %i )", [parseError code]];
	NSLog(@"error parsing XML: %@", errorString);
	
	UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[errorAlert show];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
	//NSLog(@"found this element: %@", elementName);
	currentElement = [elementName copy];
	
	if ([elementName isEqualToString:@"item"]) {
		// clear out our story item caches...
		item = [[NSMutableDictionary alloc] init];
		currentTitle = [[NSMutableString alloc] init];
		currentLink = [[NSMutableString alloc] init];
		currentLink = [[NSMutableString alloc] init];
		currentDate = [[NSMutableString alloc] init];
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	
	//NSLog(@"ended element: %@", elementName);
	if ([elementName isEqualToString:@"item"]) {
		// save values to an item, then store that item into the array...
		[item setObject:currentTitle forKey:@"title"];
		[item setObject:currentLink forKey:@"description"];
		[item setObject:currentLink forKey:@"link"];
		[item setObject:currentDate forKey:@"pubDate"];
		[items addObject:[item copy]];
		NSLog(@"adding item: %@", currentTitle);
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
	//NSLog(@"found characters: %@", string);
	// save the characters for the current item...
	if ([currentElement isEqualToString:@"title"]) [currentTitle appendString:string];
	else if ([currentElement isEqualToString:@"description"]) [currentLink appendString:string];
	else if ([currentElement isEqualToString:@"link"]) [currentLink appendString:string];
	else if ([currentElement isEqualToString:@"pubDate"]) [currentDate appendString:string];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
	
	[activityIndicator stopAnimating];
	[activityIndicator removeFromSuperview];
	
	NSLog(@"all done!");
	NSLog(@"items array has %d items", [items count]);
	[xmlTable reloadData];
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [items count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSInteger DateTag = 1;
	static NSInteger TitleTag = 2;
	
	static NSString *MyIdentifier = @"MyIdentifier";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
		CGRect frame;
		frame.origin.x = 10;
		frame.origin.y = 5;
		frame.size.height = 15;
		frame.size.width = 295;
		
		UILabel *TitleLabel = [[UILabel alloc] initWithFrame:frame];
		TitleLabel.tag = TitleTag;
		TitleLabel.font = [UIFont boldSystemFontOfSize:14];
		[cell.contentView addSubview:TitleLabel];
		[TitleLabel release];
		
		frame.origin.y += 21;
		UILabel *DateLabel = [[UILabel alloc] initWithFrame:frame];
		DateLabel.tag = DateTag;
		DateLabel.textColor = [UIColor grayColor];
		DateLabel.font = [UIFont systemFontOfSize:12];
		//DateLabel
		[cell.contentView addSubview:DateLabel];
		[DateLabel release];
		
		
	}
	
	int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
	
	UILabel * TitleLabel = (UILabel *) [cell.contentView viewWithTag:TitleTag];
	UILabel * DateLabel = (UILabel *) [cell.contentView viewWithTag:DateTag];
	
	TitleLabel.text = [[items objectAtIndex: storyIndex] objectForKey: @"title"];
	DateLabel.text = [[items objectAtIndex: storyIndex] objectForKey: @"pubDate"];
	
	return cell;
	
}

//- (void) tableView:(UITableView *) tableView touchesBegan

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if ([searchBar isFirstResponder]) [searchBar resignFirstResponder];
	
	int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
	
	RssDetailController *controller = [[RssDetailController alloc] init];
	
	controller.title = [[items objectAtIndex: storyIndex] objectForKey: @"title"];
	controller.myTitle = [[items objectAtIndex: storyIndex] objectForKey: @"title"];
	controller.myDescription = [[items objectAtIndex: storyIndex] objectForKey: @"description"];
	controller.myDate = [[items objectAtIndex: storyIndex] objectForKey: @"pubDate"];
	controller.myLink = [[items objectAtIndex: storyIndex] objectForKey: @"link"];
	//[self hidesBottomBarWhenPushed: YES];
	[[self navigationController] pushViewController:controller animated:YES];
	[controller release], controller = nil;
	
	
	
}



/*
 
 - (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
 if (searchBar) {
 [searchBar resignFirstResponder];
 //[self updateLabel];
 //if (moveViewUp) [self scrollTheView:NO];
 }
 [super touchesBegan: touches withEvent: event];
 }
 
 
 
 
 */



- (void)viewDidAppear:(BOOL)animated {
	//[self setNavigationBarHidden: NO];
    [super viewDidAppear:animated];
	//[UIApplication sharedApplication].statusBarHidden = YES;
	[NSThread detachNewThreadSelector:@selector(doGetData) toTarget:self withObject:nil];
	//[self doGetData: searchString];
	cellSize = CGSizeMake([xmlTable bounds].size.width, 60);
}







/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [currentElement release];
	[xmlParser release];
	[items release];
	[item release];
	[currentTitle release];
	[currentDate release];
	[currentLink release];
	[currentDescription release];
	[super dealloc];
	
}


@end
